from .log import log
import osso
import gobject
import charger

context = osso.Context("podcaster", "0.0.1", False)
device = osso.DeviceState(context)
timer = None

def TurnOnScreen():
  global device
  device.display_state_on()
  device.display_blanking_pause()

def Update():
  log("Screensaver keeper offer running")
  if charger.IsConnected():
    log("Charger connected. Keeping display on.")
    TurnOnScreen()
    return True
  else:
    log("Charger not connected. Canceling timer and doing squat.")
    # Unset the timer var so that next time the charger is
    # connected the timer will be set again.
    global timer
    timer = None
    return False

def Start():
  def BeginTimer():
    # This callback runs in the same thread as Update(), so there
    # is no race condition between the Update() setting the global
    # 'timer' variable and this function testing/setting it.

    # Only create a timer if there's not already one present. This
    # is to prevent creating two timers when the charger is
    # connected twice in rapid succession.
    global timer
    log("ScreenSaver BeginTimer() called. Timer is", timer)
    if timer is None:
      log("Starting the screensaver keeper offer timer.")
      # Run Update every 30 seconds to remind the device not to
      # blank the screen while the charger is connected.
      timer = gobject.timeout_add(30000, Update)
  charger.AddCallback(BeginTimer, None)

TurnOnScreen()
